<?php

namespace App\Repository;
use App\Exceptions\BusinessException;
use App\Models\Role\Role;
use App\Models\User\User;

/**
 * 用户数据仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class UserRepository extends BaseRepository
{
    /**
     * 获取用户信息
     *
     * @param int $userId
     * @return
     */
    public function getById(int $userId)
    {
        return User::query()->where('user_id', $userId)->first();
    }

    /**
     * 获取用户角色信息
     *
     * @param int $userId
     * @return
     */
    public function getUserRole(int $userId)
    {
        $roleIds = $this->getById($userId)->role_id;
        $roles = collect($roleIds)->map(function ($roleId) {
            return RoleRepository::getInstance()->getById($roleId);
        });
        return $roles;
    }

    /**
     * 获取用户列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getList(array $filter = [])
    {
        $query = User::query()->orderByDesc('created_at');
        if(!empty($filter['username'])) {
            $query->where('username', 'like', '%' . $filter['username'] . '%');
        }
        if(!empty($filter['name'])) {
            $query->where('name', 'like', '%' . $filter['name'] . '%');
        }
        return $query;
    }

    /**
     * 保存用户
     *
     * @param array $data
     * @param int $userId
     * @return int|mixed
     */
    public function update(array $data, int $userId)
    {
        $query = $userId ? User::find($userId) : new User();
        foreach ($data as $field => $value) {
            $query->{$field} = $value;
        }
        return $query->save() ? $query->user_id : 0;
    }

    /**
     * 根据用户名获取用户
     *
     * @param string $username
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getByUsername(string $username)
    {
        return User::query()->where('username', $username)->first();
    }

    /**
     * 删除用户
     *
     * @param int $userId
     * @return mixed
     */
    public function delete(int $userId)
    {
        return User::query()->where('user_id', $userId)->delete();
    }
}
